<template>
  <view class="weather-bar">
    <!-- 加载状态 -->
    <view v-if="!weatherData" class="loading">加载中...</view>
    
    <!-- 天气信息展示 -->
    <view v-else class="weather-info">
      <view class="location">{{ location }}</view>
      <view class="temperature">
        <span class="temp">{{ currentTemp }}</span>
      </view>
      <view class="condition">{{ weatherCondition }}</view>
      <view class="pm25">PM2.5 {{ pm25Value }}</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      weatherData: null,
      location: '桂林' // 默认城市
    }
  },
  mounted() {
    this.getWeather();
  },
  computed: {
    // 当前温度
    currentTemp() {
      return this.weatherData?.data?.wendu + '°C' || '';
    },
    // 天气状况
    weatherCondition() {
      return this.weatherData?.data?.forecast[0]?.type || '';
    },
    // PM2.5值
    pm25Value() {
      return this.weatherData?.data?.pm25 || '';
    }
  },
  methods: {
    getWeather() {
      // 桂林的城市代码
      uni.request({
        url: 'http://t.weather.sojson.com/api/weather/city/101300501',
        method: 'GET',
        success: (res) => {
          this.weatherData = res.data;
        },
        fail: (err) => {
          console.error('天气请求失败', err);
        }
      });
    }
  }
}
</script>

<style scoped>
.weather-bar {
  width: 100%;
  height: 45px;
  background-color: #e53e3e; /* 红色背景 */
  color: white;
  display: flex;
  align-items: center;
  padding: 0 15px;
  box-sizing: border-box;
  font-size: 14px;
}

.loading {
  width: 100%;
  text-align: center;
  color: white;
}

.weather-info {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 15px;
}

.location {
  font-weight: 500;
}

.temperature {
  margin-left: 5px;
}

.temp {
  font-size: 16px;
  font-weight: bold;
}

.condition {
  margin-left: 5px;
}

.pm25 {
  margin-left: auto; /* 推到最右侧 */
  opacity: 0.9;
}
</style>